/*************************************************************************
**************************************************************************
**************************************************************************
    MACOUI by Iktwo - Get the organization behing a MAC address
    Copyright (C) 2012  Iktwo Sh iktwo@ovi.com

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************
**************************************************************************
**************************************************************************/

#include "wmain.h"

#define WLANCOND_SERVICE "com.nokia.wlancond"
#define WLANCOND_REQ_PATH "/com/nokia/wlancond/request"
#define WLANCOND_REQ_INTERFACE "com.nokia.wlancond.request"
#define WLANCOND_SCAN_REQ "scan"
#define WLANCOND_SIG_PATH "/com/nokia/wlancond/signal"
#define WLANCOND_SIG_INTERFACE "com.nokia.wlancond.signal"
#define WLANCOND_SCAN_RESULTS_SIG "scan_results"


WMain::WMain(QWidget *parent){
    view = new QDeclarativeView(parent);

    rootContext = view->rootContext();
    rootContext->setContextProperty("wMain", this);

    rootContext->setContextProperty("appName",QApplication::applicationName());
    rootContext->setContextProperty("appOrg",QApplication::organizationName());
    rootContext->setContextProperty("appVersion",QApplication::applicationVersion());

    view->setAttribute(Qt::WA_OpaquePaintEvent);
    view->setAttribute(Qt::WA_NoSystemBackground);

    view->setSource(QUrl("qrc:/qml/main.qml"));

    view->showFullScreen();

    //Connect the "scan_result" signal
    QDBusConnection::systemBus().connect(WLANCOND_SERVICE, WLANCOND_SIG_PATH, WLANCOND_SIG_INTERFACE, WLANCOND_SCAN_RESULTS_SIG, this, SLOT(wlanScanResults(QDBusMessage)));
    startScan();
}

void WMain::startScan(){
    qDebug() << "Scanning..";
    QDBusInterface iface(WLANCOND_SERVICE,
                         WLANCOND_REQ_PATH,
                         WLANCOND_REQ_INTERFACE,
                         QDBusConnection::systemBus());
    QDBusMessage reply = iface.call(WLANCOND_SCAN_REQ, 4, QByteArray("") ,2);
}

void WMain::wlanScanResults(const QDBusMessage &status){
    networksList.clear();

    //The first argument it's the number of networks found
    int total_networks = status.arguments().at(0).toInt();

    for(int i = 0; i < total_networks; ++i){
        int offset = i * 5 + 1;
        QString essid = status.arguments().at(offset++).toString();
        QByteArray bssidBytes = status.arguments().at(offset++).toByteArray();
        offset++;
        uint channel = status.arguments().at(offset++).toInt();

        QString bssid;
        bssid.sprintf("%02X:%02x:%02x:%02x:%02x:%02x",bssidBytes.at(0),bssidBytes.at(1),bssidBytes.at(2),bssidBytes.at(3),bssidBytes.at(4),bssidBytes.at(5));
        QString oui=bssid.mid(0,8);
        QString org = getOrg(oui.toUpper());
        //qDebug() << ">> The org for OUI " << oui << " is " << org;

        addNetwork(essid,bssid.toUpper(),channel,org);
    }
}

void WMain::addNetwork(QString essid, QString bssid, int channel,QString org){
    networksList.append(new NetworkDetails(essid,bssid,channel,org));
    rootContext->setContextProperty("networksModel", QVariant::fromValue(networksList));
}

QString WMain::getOrg(QString oui){
    QString orgTxt;
    if (oui.simplified().count()>2){
        QFile *file=new QFile("/opt/macoui/data/oui.txt");
        if (file->open(QIODevice::ReadOnly | QIODevice::Text)){
            QTextStream *t= new QTextStream(file);
            int i=0;
            QString line;
            while ( !t->atEnd() ) {
                i++;
                line=t->readLine();
                if (line.indexOf(oui.replace(":","-"))!=-1){
                    orgTxt=(line.mid(line.indexOf("(hex)")+5).simplified());
                    file->close();
                    delete file;
                    delete t;
                    return orgTxt;
                }else if (i==16104){
                    orgTxt="Org. not found :(";
                    file->close();
                    delete file;
                    delete t;
                    return orgTxt;
                }
            }
            file->close();
            delete t;
        }
        delete file;

    }else{
        return "";
    }
}
